package com.example.demo.handler;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;

public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, FullHttpRequest msg) throws Exception {
        System.out.println(msg);
        String uri = msg.getUri().equals("/")?"chat.html":msg.getUri();
        RandomAccessFile randomAccessFile ;
        try{
           randomAccessFile = new RandomAccessFile(getResourcePath(uri),"r");
        } catch (Exception e){
            channelHandlerContext.fireChannelRead(msg.retain());
            return;
        }
        HttpResponse httpResponse = new DefaultHttpResponse(msg.getProtocolVersion(), HttpResponseStatus.OK);
        httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE,"text/html");
        boolean iskeepAlive = HttpHeaders.isKeepAlive(msg);
        if (iskeepAlive){
            httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH,randomAccessFile.length());
            httpResponse.headers().set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.KEEP_ALIVE);
        }
        channelHandlerContext.write(httpResponse);

        channelHandlerContext.write(new ChunkedNioFile(randomAccessFile.getChannel()));
        ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!iskeepAlive){
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        }
        randomAccessFile.close();
    }

    public String getResourcePath(String uri) throws URISyntaxException {
        URL url = HttpHandler.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println("URL:" + url.toURI());
        String path = url.toURI()+ "templates" + "/" + uri;
        path = path.replace("file:/","");
        System.out.println(path);
        return path;
    }
}
